package com.ebao.action.user;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.ebao.action.base.BaseAction;
import com.ebao.constants.WebConstants;
import com.ebao.po.user.TUser;
import com.ebao.service.talk.ITalkService;
import com.ebao.service.user.IUserService;
import com.ebao.vo.Talk;

/**
 * @author snow
 */
public class UserAction extends BaseAction {

	private static final long serialVersionUID = -4643349923815024953L;
	
	@Resource
	private IUserService userService;
	@Resource
	private ITalkService talkService;
	
	private String userId;
	private String userEmail;
	private String userpass;
	
	private String jsonInfo;
	
	/**
	 * 用户登录,跳转至个人首页
	 */
	@Action(value = "login", results = {@Result(name = SUCCESS, location = "userhome.jsp"),
			@Result(name = ERROR, location = "/index.jsp")})
	public String login(){
		String jpql = "from TUser u where u.email=? and u.password=?";
		TUser user = null;
		if(StringUtils.isNotBlank(userEmail)){
			user = userService.getByJpql(jpql, userEmail.trim(), userpass.trim());
		}
		if(user != null){
			List<Talk> talkList = talkService.getUserTalkList(user);//用户的说说列表，跳转至用户首页显示
			request.put("talkList", talkList);
			session.put(WebConstants.LOGIN_USER, user);
			// 将登录时间设置进session中，用于获取最新的说说，每次获取以后重新设置该信息
			session.put("loginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			return SUCCESS;
		} else {
			jsonInfo = "邮箱或密码不匹配";
			return ERROR;
		}
	}
	
	/**
	 * 用户跳转至设置密码页
	 */
	@Action(value = "goto-setPassword", results = {@Result(name = SUCCESS, 
			location = "userset.jsp?fpage=passSet.jsp")})
	public String gotoSetPassword(){
		return SUCCESS;
	}
	
	/**
	 * 用户设置密码
	 */
	@Action(value = "save-password", results = {@Result(name = SUCCESS, 
			type = "json", params = {"root","jsonInfo"})})
	public String savePassword(){
		TUser user = userService.getById(userId);
		user.setPassword(userpass.trim());
		userService.update(user);
		jsonInfo = "密码设置成功";
		return SUCCESS;
	}
	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserEmail() {
		return userEmail;
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}

	public String getUserpass() {
		return userpass;
	}

	public void setUserpass(String userpass) {
		this.userpass = userpass;
	}

	public String getJsonInfo() {
		return jsonInfo;
	}

	public void setJsonInfo(String jsonInfo) {
		this.jsonInfo = jsonInfo;
	}
	
}
